package com.gopay.scheduler.job;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.OrderLifecycleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IntegrationPayOrdersTimeoutCleanJob extends GopayBaseJob {
    public static final String TRANSTYPE = "02301";
    private Logger logger = LoggerFactory.getLogger(IntegrationPayOrdersTimeoutCleanJob.class);
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;
    private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

    private static final int QUERYCOUNT = 5000;

    // private static final int REMAINDER = QUERYCOUNT -1;
    @Resource(name = "cpsGeneralMainOrderOperClient")
    public void setCpsGeneralMainOrderOperClient(MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient) {
        this.cpsGeneralMainOrderOperClient = cpsGeneralMainOrderOperClient;
    }

    @Resource(name = "cpsGeneralMainOrderDAO")
    public void setCpsGeneralMainOrderDAO(CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO) {
        this.cpsGeneralMainOrderDAO = cpsGeneralMainOrderDAO;
    }

    @Override
    public void doJobInternal() {
        logger.error("----聚合支付、小额免密支付撤销超时订单处理开始----");
        long startMillions = 0;
        try {
            Map param = new HashMap();
            String b2cName = TRANSTYPE + OrderLifecycleUtil.B2C;
            String b2c = OrderLifecycleUtil.getLifecycle(b2cName);
            param.put("b2c", b2c);
            // 每次1000条
            startMillions = System.currentTimeMillis();
            logger.info("查询超时订单执行开始 ");
            List<Object> orderList = findTimeoutOrdersIntegrationPay(param, 1, QUERYCOUNT);
            updateStatus(orderList);
        } catch (Exception e) {
            logger.error("聚合支付、小额免密支付撤销超时订单处理异常信息", e.getMessage());
        }
        long endMiilions = System.currentTimeMillis();
        long result = (endMiilions - startMillions) / 1000;
        logger.info("超时订单执行结束 耗费=" + result + "秒");
    }

    private void updateStatus(List<Object> orderList) {
        if (!(orderList.isEmpty())) {
            String txnStaCode = String.valueOf(TxnStaCode.TXN_STA_CD_20002.value);
            logger.info("pay timeout orders Id:" + orderList.toString());
            logger.info("found" + orderList.size() + "other orders  records, overtime timeout order clean-up work now!");

            Map<MainOrderField, String> map = new HashMap<MainOrderField, String>();

            map.put(MainOrderField.TXN_STA_CD, txnStaCode);
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            map.put(MainOrderField.TRAN_FINISH_TIME, sf.format(new Date()));
            for (Object obj : orderList) {

                String gopayOrderId = String.valueOf(obj);
                try {
                    cpsGeneralMainOrderOperClient.updateMany(gopayOrderId, map);
                } catch (GopayException e) {
                    logger.error("update order fail,orderId:" + gopayOrderId.toString(), e);
                } catch (Exception e) {
                    logger.error("update order fail,orderId:" + gopayOrderId, e);
                }

            }

        }
    }

    /**
     * 聚合支付&小额免密超时订单
     */
    private List<Object> findTimeoutOrdersIntegrationPay(Map param, int pageNo, int pageSize) {
        StringBuffer sb = new StringBuffer("select gopay_order_id from CPS_GEN_MAIN_ORDER ");
        sb.append(" where ACCOUNTING_POINT is null and TXN_STA_CD in('"
                + String.valueOf(TxnStaCode.TXN_STA_CD_30000.value)
                + "','"
                + String.valueOf(TxnStaCode.TXN_STA_CD_30101.value)
                + "')");
        sb.append(" and GOPAY_INT_TXN_CD in ('02301', '02302') ");
        sb.append(" and TRUNC(TO_NUMBER(SYSDATE - (CREATED_TS+0))*24*60)>=:timeSpan ");
        Map m = new HashMap();
        m.put("timeSpan",
                String.valueOf(param.get("b2c")).replaceAll("[a-zA-Z]+", ""));
        List<?> result = cpsGeneralMainOrderDAO.findBySql(sb.toString(), m, pageNo, pageSize);
        return (List<Object>) result;
    }
}
